package com.flow.framework.core.service.system.health.impl;

import com.flow.framework.common.health.ServiceHealthCheckCode;
import com.flow.framework.common.pojo.vo.system.ServiceHealthVo;
import com.flow.framework.common.service.system.health.IHealthCheckService;
import com.flow.framework.common.util.verify.VerifyUtil;
import com.flow.framework.core.system.thread.pool.executor.SystemStatusCheckerExecutor;
import com.flow.framework.core.system.helper.SystemHealthHelper;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * 系统状态健康检查
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/2/5
 */
@Slf4j
public class ServiceStatusHealthCheckServiceImpl implements IHealthCheckService {

    /**
     * @inheritDoc
     */
    @Override
    public List<ServiceHealthVo> check() {
        List<ServiceHealthVo> serviceHealthVos = new ArrayList<>();
        try {
            Map<Integer, Set<String>> healthCheckCodeAndUnhealthyTagsMap = SystemStatusCheckerExecutor
                    .getHealthCheckCodeAndUnhealthyTagsMap();
            healthCheckCodeAndUnhealthyTagsMap.forEach((healthCheckCode, unhealthyTags) -> {
                if (VerifyUtil.isEmpty(unhealthyTags)) {
                    SystemHealthHelper.healthy(healthCheckCode);
                    return;
                }
                serviceHealthVos.add(
                        SystemHealthHelper.unhealthy(healthCheckCode, null, new ArrayList<>(unhealthyTags))
                );
            });
            return serviceHealthVos;
        } catch (Exception e) {
            log.error("check discovery remote error.", e);
            return Collections.singletonList(
                    SystemHealthHelper.unhealthy(ServiceHealthCheckCode.SERVICE_HEALTH_CHECK_CODE, e.getMessage(), null)
            );
        }
    }
}
